package com.mysterymall.Service.Impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysterymall.Common.Comp.HttpStatus;
import com.mysterymall.Common.Comp.LocalCache;
import com.mysterymall.Common.Utils.BaseEnum;
import com.mysterymall.Common.Utils.CommonException;
import com.mysterymall.Common.Utils.Result;
import com.mysterymall.Mapper.*;
import com.mysterymall.Model.Dto.GoodsDto;
import com.mysterymall.Model.Dto.SelectGoodsDto;
import com.mysterymall.Model.Entity.*;
import com.mysterymall.Model.Vo.GoodsVo;
import com.mysterymall.Model.Vo.ShowGoodsMonomerVo;
import com.mysterymall.Model.Vo.ShowGoodsVo;
import com.mysterymall.Model.Vo.UserGoodsVo;
import com.mysterymall.Service.GoodsService;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.*;

import java.util.Locale;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName com.mysterymall.Service.Impl
 * @Description
 * @Author HuangWX
 * @Time 2023/11/04  00:37
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    private final GoodsMapper goodsMapper;


    private final GoodsTypeMapper goodsTypeMapper;


    private final GoodsAttributeMapper goodsAttributeMapper;


    private final MoneyTypeMapper moneyTypeMapper;


    private final BoxGroupGoodsMapper boxGroupGoodsMapper;

    private final UserGoodsMapper userGoodsMapper;

    private final UserMapper userMapper;


    private final GameCurrencyDetailMapper gameCurrencyMapper;

    /**
     * 构造器注入
     *
     * @param goodsMapper         商品映射器
     * @param goodsTypeMapper     商品类别映射器
     * @param goodsAttributeMapper 商品属性映射器
     * @param moneyTypeMapper     货币类型映射器
     * @param boxGroupGoodsMapper 盒子组合商品映射器
     * @param userGoodsMapper     用户商品映射器
     * @param userMapper          用户映射器
     * @param gameCurrencyMapper  游戏币映射器
     */
    public GoodsServiceImpl(GoodsMapper goodsMapper, GoodsTypeMapper goodsTypeMapper, GoodsAttributeMapper goodsAttributeMapper,
                            MoneyTypeMapper moneyTypeMapper, BoxGroupGoodsMapper boxGroupGoodsMapper, UserGoodsMapper userGoodsMapper,
                            UserMapper userMapper, GameCurrencyDetailMapper gameCurrencyMapper) {
        this.goodsMapper = goodsMapper;
        this.goodsTypeMapper = goodsTypeMapper;
        this.goodsAttributeMapper = goodsAttributeMapper;
        this.moneyTypeMapper = moneyTypeMapper;
        this.boxGroupGoodsMapper = boxGroupGoodsMapper;
        this.userGoodsMapper = userGoodsMapper;
        this.userMapper = userMapper;
        this.gameCurrencyMapper = gameCurrencyMapper;
    }


    @Override
    @Transactional
    public Result addGoods(GoodsDto goodsDto) {

        if (!StpUtil.hasPermission("goods:add:*")) {
            return new Result(HttpStatus.UNAUTHORIZED, "message.powerError");
        }

        Goods goods = new Goods();

        BeanUtils.copyProperties(goodsDto, goods);

        // 创建人
        goods.setCreateUser(StpUtil.getLoginId().toString());

        // 商品类别，图片 操作
        goods = this.goodsControls(goodsDto, goods);

        goodsMapper.insert(goods);


        // 规格_256G#颜色_绿色,10_10
        // 颜色&warna&color_绿色&hijau&green#规格&Spesifikasi&specifications_215G&215G&215G,10_10

        // 属性操作
        this.attributeControls(goodsDto, goods, null);

        return Result.success("message.addSuccess");
    }


    @Override
    @Transactional
    public Result updateGoods(GoodsDto goodsDto) {


        if (!StpUtil.hasPermission("goods:update:*")) {
            return new Result(HttpStatus.UNAUTHORIZED, "message.powerError");
        }

        if (!StpUtil.hasPermission("goods:update:all")) {
            return new Result(HttpStatus.UNAUTHORIZED, "message.powerError");
        }

        if (goodsDto.getId() == null || goodsDto.getId().isEmpty()) {
            return Result.error("message.ParameterError");
        }

        Goods goods = goodsMapper.selectById(goodsDto.getId());


        if (goods == null) {
            return Result.error("message.ParameterError");
        }

        // 修改状态
        goods.setGoodsStatus(goodsDto.getGoodsStatus());


        // 修改名称
        goods.setGoodsName(goodsDto.getGoodsName());


        // 类别，图片 操作
        goods = this.goodsControls(goodsDto, goods);


        // 删除原来的商品属性
        QueryWrapper<GoodsAttribute> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", goods.getId());

        List<GoodsAttribute> goodsAttributes = goodsAttributeMapper.selectList(queryWrapper);
        goodsAttributeMapper.delete(queryWrapper);

        // 属性操作
        this.attributeControls(goodsDto, goods, goodsAttributes);

        // 更新商品
        goodsMapper.updateById(goods);

        return Result.success("message.updateSuccess");

    }

    @Override
    public Result getAllGoods(Integer current, Integer size) {

        if (!StpUtil.hasPermission("goods:select:all")) {
            return new Result(HttpStatus.UNAUTHORIZED, "message.powerError");
        }

        Page<Goods> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);
        page.setMaxLimit(50L);

        Page<Goods> goodsList = goodsMapper.selectAll(page);

        List<GoodsVo> goodsVos = new ArrayList<>();
        for (Goods goods :
                goodsList.getRecords()) {
            GoodsVo goodsVo = new GoodsVo();
            BeanUtils.copyProperties(goods, goodsVo);
            goodsVo.setCreateTime(goods.getShanghaiCreateTime());
            StringBuilder goodsTypeString = new StringBuilder();
            for (String goodsTypeId :
                    goods.getGoodsType().split("_")) {
                GoodsType goodsType = goodsTypeMapper.selectById(goodsTypeId);
                goodsTypeString.append("#").append(goodsType.getTypeName());
            }

            // 查询总数量
            QueryWrapper<GoodsAttribute> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("goods_id", goods.getId());
            List<GoodsAttribute> goodsAttributes = goodsAttributeMapper.selectList(queryWrapper);
            int goodsCount = 0;
            for (GoodsAttribute goodsAttribute :
                    goodsAttributes) {
                goodsCount += goodsAttribute.getGoodsCount();
            }
            goodsVo.setGoodsCount(goodsCount);
            goodsVo.setGoodsType(goodsTypeString.substring(1, goodsTypeString.length()));
            goodsVos.add(goodsVo);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("list", goodsVos);
        map.put("total", goodsList.getTotal());
        return new Result(HttpStatus.SUCCESS, "message.querySuccess", map);
    }

    @Override
    public Result getByTypeList(String goodsTypeId, HttpServletRequest request) {

        if (!StpUtil.hasPermission("goods:select:*")) {
            return new Result(HttpStatus.UNAUTHORIZED, "message.powerError");
        }

        return null;
    }

    @Override
    public Result deleteGoods(String id) {

        if (!StpUtil.hasPermission("goods:delete:*")) {
            return new Result(HttpStatus.UNAUTHORIZED, "message.powerError");
        }

        if (id == null || "".equals(id)) {
            return Result.error("message.ParameterError");
        }
        goodsMapper.deleteById(id);

        QueryWrapper<GoodsAttribute> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", id);
        goodsAttributeMapper.delete(queryWrapper);

        return Result.success("message.deleteSuccess");
    }

    @Override
    public Result getShopList(Integer page, HttpServletRequest request) {

        // 查询商品列表
        Page<Goods> goodsPage = new Page<>();
        goodsPage.setCurrent(page);
        goodsPage.setSize(10);
        goodsPage.setMaxLimit(50L);

        // 查询商品状态为上架的商品
        Page<Goods> goodsList = goodsMapper.selectByStatusAndNum(goodsPage, 1);


        Map<String, Object> map = new HashMap<>();

        List<ShowGoodsVo> showGoodsVos = new ArrayList<>();
        for (Goods goods : goodsList.getRecords()) {

            ShowGoodsVo showGoodsVo = new ShowGoodsVo();
            // 展示商品处理
            showGoodsVo = this.showGoodsControls(goods, showGoodsVo, request);
            showGoodsVos.add(showGoodsVo);
        }
        map.put("total", goodsList.getTotal());
        map.put("list", showGoodsVos);
        return new Result(HttpStatus.SUCCESS, "message.querySuccess", map);
    }

    @Override
    public Result getGoodsAttribute(String goodsId, HttpServletRequest request) {

        if (!StpUtil.hasPermission("goods:select:*")) {
            return new Result(HttpStatus.UNAUTHORIZED, "message.powerError");
        }

        if (goodsId == null || "".equals(goodsId)) {
            return Result.error("message.ParameterError");
        }

        Goods goods = goodsMapper.selectById(goodsId);

        if (goods == null) {
            return Result.error("message.ParameterError");
        }

        // 查询商品属性, 0为查询出多语言 1为查询出单体语言
        Map<String, Object> map = this.getGoodsAttributeControls(goodsId, 1, request);

        return Result.success("message.querySuccess", map);
    }

    /**
     * 根据商品ID查询商品单体详情( 管理员 )
     *
     * @param goodsId
     * @return
     */
    @Override
    public Result getMonomerGoods(String goodsId) {

        if (!StpUtil.hasPermission("goods:select:*")) {
            return new Result(HttpStatus.UNAUTHORIZED, "message.powerError");
        }

        // 查询商品
        Goods goods = goodsMapper.selectById(goodsId);

        if (goods == null) {
            return Result.error("message.ParameterError");
        }

        GoodsVo goodsVo = new GoodsVo();

        BeanUtils.copyProperties(goods, goodsVo);

//        StringBuilder goodsTypeString = new StringBuilder();
//        for (String goodsTypeId :
//                goods.getGoodsType().split("_")) {
//            GoodsType goodsType = goodsTypeMapper.selectById(goodsTypeId);
//            goodsTypeString.append("#").append(goodsType.getTypeName()).append("&").append(goodsType.getCategory());
//        }

        // 查询总数量
        QueryWrapper<GoodsAttribute> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", goods.getId());
        List<GoodsAttribute> goodsAttributes = goodsAttributeMapper.selectList(queryWrapper);
        int goodsCount = 0;
        for (GoodsAttribute goodsAttribute :
                goodsAttributes) {
            goodsCount += goodsAttribute.getGoodsCount();
        }

        // 商品图片
        goodsVo.setGoodsImages(goods.getGoodsImages());

        goodsVo.setGoodsCount(goodsCount);
//        goodsVo.setGoodsType(goodsTypeString.substring(1, goodsTypeString.length()));

        return Result.success("message.querySuccess", goodsVo);
    }

    @Override
    public Result getShopGoodsMonomer(String goodsId, HttpServletRequest request) {

        // 查询商品
        Goods goods = goodsMapper.selectById(goodsId);

        if (goods == null) {
            return Result.error("message.ParameterError");
        }
        ShowGoodsVo showGoodsVo = new ShowGoodsVo();

        ShowGoodsMonomerVo showGoodsMonomerVo = new ShowGoodsMonomerVo();

        // 商品处理
        showGoodsVo = this.showGoodsControls(goods, showGoodsVo, request);

        // 商品单体处理
        BeanUtils.copyProperties(showGoodsVo, showGoodsMonomerVo);

        // 查询商品属性 , 单语言
        Map<String, Object> map = this.getGoodsAttributeControls(goodsId, 0, request);

        showGoodsMonomerVo.setGoodsAttribute((List<String>) map.get("attribute"));

        showGoodsMonomerVo.setGoodsAttributeValue((List<String>) map.get("attributeValue"));

        showGoodsMonomerVo.setGoodsAttributeAssembly((List<String>) map.get("goodsAttribute"));


        showGoodsMonomerVo.setGoodsAttributeValueId((List<String>) map.get("goodsAttributeId"));

        return Result.success("message.querySuccess", showGoodsMonomerVo);
    }

    @Override
    public Result fuzzyQuery(String goodsName) {

        if (!StpUtil.hasPermission("goods:select:*")) {
            return new Result(HttpStatus.UNAUTHORIZED, "message.powerError");
        }

        if (goodsName == null || "".equals(goodsName)) {
            return Result.error("message.ParameterError");
        }

        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("goods_name", goodsName);
        List<Goods> goodsList = goodsMapper.selectList(queryWrapper);

        List<GoodsVo> goodsVos = new ArrayList<>();

        for (Goods goods :
                goodsList) {
            GoodsVo goodsVo = new GoodsVo();
            BeanUtils.copyProperties(goods, goodsVo);
            goodsVo.setCreateTime(goods.getShanghaiCreateTime());
            goodsVos.add(goodsVo);
        }


        return Result.success("message.querySuccess", goodsVos);
    }

    @Override
    public Result getGoodsTypeGoodsList(SelectGoodsDto selectGoodsDto, HttpServletRequest request) {


        GoodsType goodsType = goodsTypeMapper.selectById(selectGoodsDto.getTypeId());

        if (goodsType == null) {
            return new Result(HttpStatus.BAD_NOT_PASS, "message.queryError");
        }

        Page<Goods> goodsPage = new Page<>();
        goodsPage.setCurrent(selectGoodsDto.getPage());
        goodsPage.setSize(10);
        goodsPage.setMaxLimit(50L);

        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.like(Goods::getGoodsType, goodsType.getId());

        List<Goods> goodsList = goodsMapper.selectPage(goodsPage, queryWrapper).getRecords();

        List<ShowGoodsVo> showGoodsVos = new ArrayList<>();
        for (Goods goods : goodsList) {
            ShowGoodsVo showGoodsVo = new ShowGoodsVo();
            // 展示商品处理
            showGoodsVo = this.showGoodsControls(goods, showGoodsVo, request);
            showGoodsVos.add(showGoodsVo);
        }

        return new Result(HttpStatus.SUCCESS, "message.querySuccess", showGoodsVos);
    }

    @Override
    public Result getMyUserGoods(String type, HttpServletRequest request,Integer current, Integer size) {

        if (!StpUtil.hasPermission("goods:select:*")) {
            return new Result(HttpStatus.UNAUTHORIZED, "message.powerError");
        }

        if (type == null || type.isEmpty()) {
            return new Result(HttpStatus.BAD_NOT_PASS, "message.queryError");
        }

        LambdaQueryWrapper<UserGoods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserGoods::getUserId, StpUtil.getLoginId());
        lambdaQueryWrapper.eq(UserGoods::getDeleteIsStatus, BaseEnum.Not_Delete.getCode());
        lambdaQueryWrapper.eq(UserGoods::getIsUserGoods, BaseEnum.Goods_Affiliation_User.getCode());

        Page<UserGoods> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);

        // 按照创建时间倒序
        lambdaQueryWrapper.orderByDesc(UserGoods::getCreateTime);

        if (!"all".equals(type)) {
            lambdaQueryWrapper.eq(UserGoods::getIsExchange, type);
        }
        List<UserGoods> userGoodsList = userGoodsMapper.selectPage(page, lambdaQueryWrapper).getRecords();

        List<UserGoodsVo> userGoodsVoList = new ArrayList<>();
        for (UserGoods userGoods : userGoodsList) {
            UserGoodsVo userGoodsVo = new UserGoodsVo();
            BeanUtils.copyProperties(userGoods, userGoodsVo);
            userGoodsVo.setAttributeValue("");
            switch ((String) request.getAttribute("Lang")) {
                case "zh": {
                    userGoodsVo.setGoodsName(userGoods.getGoodsName().split("_")[0]);
                    userGoodsVo.setGoodsImageDescriptZh(userGoods.getGoodsImageDescriptZh());
                    for (String attributeValue : userGoods.getAttributeValue().split("_")) {
                        userGoodsVo.setAttributeValue(userGoodsVo.getAttributeValue() + ", " + attributeValue.split("&")[0]);
                    }
                    userGoodsVo.setAttributeValue(userGoodsVo.getAttributeValue().substring(1, userGoodsVo.getAttributeValue().length()));
                    break;
                }
                case "ms": {
                    userGoodsVo.setGoodsName(userGoods.getGoodsName().split("_")[1]);
                    userGoodsVo.setGoodsImageDescriptZh(userGoods.getGoodsImageDescriptMs());
                    for (String attributeValue : userGoods.getAttributeValue().split("_")) {
                        userGoodsVo.setAttributeValue(userGoodsVo.getAttributeValue() + ", " + attributeValue.split("&")[1]);
                    }
                    userGoodsVo.setAttributeValue(userGoodsVo.getAttributeValue().substring(1, userGoodsVo.getAttributeValue().length()));
                    break;
                }
                case "en": {
                    userGoodsVo.setGoodsName(userGoods.getGoodsName().split("_")[2]);
                    userGoodsVo.setGoodsImageDescriptZh(userGoods.getGoodsImageDescriptEn());
                    for (String attributeValue : userGoods.getAttributeValue().split("_")) {
                        userGoodsVo.setAttributeValue(userGoodsVo.getAttributeValue() + ", " + attributeValue.split("&")[2]);
                    }
                    userGoodsVo.setAttributeValue(userGoodsVo.getAttributeValue().substring(1, userGoodsVo.getAttributeValue().length()));
                    break;
                }
            }
            userGoodsVo.setExchangeTime(userGoods.getExchangeTime());
            userGoodsVoList.add(userGoodsVo);
        }
        return new Result(HttpStatus.SUCCESS, "message.querySuccess", userGoodsVoList);
    }

    @Override
    @Transactional
    public Result goodsExchange(String goodsId) {

        if (!StpUtil.hasPermission("userGoods:exchange:*")) {
            return new Result(HttpStatus.UNAUTHORIZED, "message.powerError");
        }

        if (goodsId == null || goodsId.isEmpty()) {
            return new Result(HttpStatus.BAD_NOT_PASS, "message.queryError");
        }

        UserGoods userGoods = userGoodsMapper.selectById(goodsId);

        // 判断是否存在
        if (userGoods == null) {
            return new Result(HttpStatus.BAD_NOT_PASS, "message.queryError");
        }

        // 判断是否已经兑换
        if (BaseEnum.Goods_Yes_Exchange.getCode().equals(userGoods.getIsExchange())) {
            return new Result(HttpStatus.BAD_NOT_PASS, "message.queryError");
        }

        // 将商品改为已兑换
        userGoods.setIsExchange(BaseEnum.Goods_Yes_Exchange.getCode());

        // 兑换时间
        userGoods.setExchangeTime(Instant.ofEpochMilli(new Date().getTime()));

        userGoodsMapper.updateById(userGoods);

        User user = userMapper.selectById(StpUtil.getLoginId().toString());

        // 游戏币明细记录
        GameCurrencyDetail gameCurrencyDetail = new GameCurrencyDetail();
        // 商品名称
        gameCurrencyDetail.setGoodsName(userGoods.getGoodsName());
        gameCurrencyDetail.setUserId(user.getId());
        // 类型-收入
        gameCurrencyDetail.setType(BaseEnum.Game_Currency_Income.getCode());
        // 金额类型 - 商品兑换
        gameCurrencyDetail.setAmountType(BaseEnum.Game_Currency_Type_Goods_Exchange.getCode());
        // 金额
        gameCurrencyDetail.setAmount(userGoods.getGoodsAmount());
        gameCurrencyMapper.insert(gameCurrencyDetail);

        // 用户金额增加
        user.setAmount(user.getAmount().add(userGoods.getGoodsAmount()));

        userMapper.updateById(user);

        return new Result(HttpStatus.SUCCESS, "message.querySuccess");

    }


    /**
     * 商品属性处理
     *
     * @param goodsId 商品Id
     * @param type    0 单语言   1 多语言
     * @return Map
     */
    public Map<String, Object> getGoodsAttributeControls(String goodsId, Integer type, HttpServletRequest request) {

        // 查询商品属性
        QueryWrapper<GoodsAttribute> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", goodsId);
        List<GoodsAttribute> goodsAttributes = goodsAttributeMapper.selectList(queryWrapper);

        // 属性
        List<String> goodsAttributeList = new ArrayList<>();

        // 属性值
        List<String> attributeList = new ArrayList<>();

        // 属性值组合
        List<String> attributeValueList = new ArrayList<>();

        // 属性值组合Id
        List<String> goodsAttributeIdList = new ArrayList<>();

        for (GoodsAttribute goodsAttribute :
                goodsAttributes) {

            goodsAttributeIdList.add(goodsAttribute.getId());
            if (attributeList.size() == 0) {
                if (type == 0) {
                    String[] attribute = goodsAttribute.getAttributeName().split("_");

                    // attribute 的长度有多少个属性，就有多少个属性值
                    switch ((String) request.getAttribute("Lang")) {
                        case "zh": {
                            for (int i = 0; i < attribute.length; i++) {
                                attribute[i] = attribute[i].split("&")[0];
                            }
                            break;
                        }
                        case "ms": {
                            for (int i = 0; i < attribute.length; i++) {
                                attribute[i] = attribute[i].split("&")[1];
                            }
                            break;
                        }
                        case "en": {
                            for (int i = 0; i < attribute.length; i++) {
                                attribute[i] = attribute[i].split("&")[2];
                            }
                            break;
                        }
                    }
                    attributeList.addAll(Arrays.asList(attribute));
                } else {
                    attributeList.addAll(Arrays.asList(goodsAttribute.getAttributeName().split("_")));
                }
            }
            StringBuilder text = new StringBuilder();
            int index = 0;
            for (String name : goodsAttribute.getAttributeName().split("_")) {
                text.append("#").append(name).append("_").append(goodsAttribute.getAttributeValue().split("_")[index]);
                StringBuilder value = new StringBuilder();
                value.append(name).append("_").append(goodsAttribute.getAttributeValue().split("_")[index]);
                // 如果值不存在，添加到 attributeValueList 中
                if (type == 0) {
                    switch ((String) request.getAttribute("Lang")) {
                        case "zh": {
                            value = new StringBuilder(name.split("&")[0] + "_" + goodsAttribute.getAttributeValue().split("_")[index].split("&")[0]);
                            break;
                        }
                        case "ms": {
                            value = new StringBuilder(name.split("&")[1] + "_" + goodsAttribute.getAttributeValue().split("_")[index].split("&")[1]);
                            break;
                        }
                        case "en": {
                            value = new StringBuilder(name.split("&")[2] + "_" + goodsAttribute.getAttributeValue().split("_")[index].split("&")[2]);
                            break;
                        }
                    }
                    if (!attributeValueList.contains(value.toString())) {
                        attributeValueList.add(value.toString());
                    }
                } else {
                    if (!attributeValueList.contains(value.toString())) {
                        attributeValueList.add(value.toString());
                    }
                }

                index++;
            }

            if (type == 1) {

            } else {
                StringBuilder stringBuilder = new StringBuilder();
                String[] textArray = text.toString().split("#");

                // 清除textArray中值为''的元素
                List<String> list = new ArrayList<>();
                for (String s : textArray) {
                    if (!"".equals(s)) {
                        list.add(s);
                    }
                }
                textArray = list.toArray(new String[list.size()]);
                switch ((String) request.getAttribute("Lang")) {
                    case "zh": {
                        // 循环加入,并将值给到string
                        for (String s : textArray) {
                            stringBuilder.append("_").append(s.split("_")[0].split("&")[0]).append("_").append(s.split("_")[1].split("&")[0]);
                        }
                        break;
                    }
                    case "ms": {
                        for (String s : textArray) {
                            stringBuilder.append("_").append(s.split("_")[0].split("&")[1]).append("_").append(s.split("_")[1].split("&")[1]);
                        }
                        break;
                    }
                    case "en": {
                        for (String s : textArray) {
                            stringBuilder.append("_").append(s.split("_")[0].split("&")[2]).append("_").append(s.split("_")[1].split("&")[2]);
                        }
                        break;
                    }
                }
                text = new StringBuilder(stringBuilder.substring(1, stringBuilder.length()));
            }
            text.append(",").append(goodsAttribute.getGoodsAmount()).append("_").append(goodsAttribute.getGoodsCount());

            if(text.toString().contains("#")){
                goodsAttributeList.add(text.substring(1, text.length()));
            }else{
                goodsAttributeList.add(text.toString());
            }
        }

        // 查询成功
        Map<String, Object> map = new HashMap<>();
        map.put("attribute", attributeList);
        map.put("attributeValue", attributeValueList);
        map.put("goodsAttributeId", goodsAttributeIdList);
        map.put("goodsAttribute", goodsAttributeList);

        return map;
    }

    /**
     * 展示商品处理
     *
     * @param goods
     * @param showGoodsVo
     * @return
     */
    public ShowGoodsVo showGoodsControls(Goods goods, ShowGoodsVo showGoodsVo, HttpServletRequest request) {

        BeanUtils.copyProperties(goods, showGoodsVo);

        // 商品名称处理
        switch ((String) request.getAttribute("Lang")) {
            case "zh":
                showGoodsVo.setGoodsName(goods.getGoodsName().split("_")[0]);
                showGoodsVo.setGoodsDescriptionImage(goods.getGoodsImageZh());
                break;
            case "ms":
                showGoodsVo.setGoodsName(goods.getGoodsName().split("_")[1]);
                showGoodsVo.setGoodsDescriptionImage(goods.getGoodsImageMs());
                break;
            case "en":
                showGoodsVo.setGoodsName(goods.getGoodsName().split("_")[2]);
                showGoodsVo.setGoodsDescriptionImage(goods.getGoodsImageEn());
                break;
        }
        // 主页图片处理
        StringBuilder imagesString = new StringBuilder();
        for (String image : goods.getGoodsImages().split("_")) {
            imagesString.append("_").append("/images/").append(image);
        }
        showGoodsVo.setGoodsImages(imagesString.substring(1, imagesString.length()));

        // 描述图片处理
        StringBuilder descriptionImagesString = new StringBuilder();
        for (String images : showGoodsVo.getGoodsDescriptionImage().split("_")) {
            descriptionImagesString.append("_").append("/images/").append(images);
        }
        showGoodsVo.setGoodsDescriptionImage(descriptionImagesString.substring(1, descriptionImagesString.length()));

        // 商品金额处理
        QueryWrapper<GoodsAttribute> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", goods.getId());
        List<GoodsAttribute> goodsAttributes = goodsAttributeMapper.selectList(queryWrapper);

        BigDecimal goodsAmount = new BigDecimal(1000000000);
        for (GoodsAttribute goodsAttribute :
                goodsAttributes) {
            if (goodsAttribute.getGoodsAmount().compareTo(new BigDecimal(0)) > 0) {
                // 查询最小的值
                if (goodsAttribute.getGoodsAmount().compareTo(goodsAmount) < 0) {
                    goodsAmount = goodsAttribute.getGoodsAmount();
                }
            }
        }
        showGoodsVo.setGoodsAmount(goodsAmount);

        // 商品类别处理
        if (goods.getGoodsType() != null && !"".equals(goods.getGoodsType())) {
            GoodsType goodsType = goodsTypeMapper.selectById(goods.getGoodsType().split("_")[0]);
            switch ((String) request.getAttribute("Lang")) {
                case "zh":
                    showGoodsVo.setGoodsType(goodsType.getTypeName().split("_")[0]);
                case "ms":
                    showGoodsVo.setGoodsType(goodsType.getTypeName().split("_")[1]);
                case "en":
                    showGoodsVo.setGoodsType(goodsType.getTypeName().split("_")[2]);
            }
            showGoodsVo.setGoodsTypeImage("/images/" + goodsType.getImage());
        }

        return showGoodsVo;
    }

    /**
     * 属性操作封装
     *
     * @param goodsDto 商品Dto
     * @param goods    商品
     */
    @Transactional
    public void attributeControls(GoodsDto goodsDto, Goods goods, List<GoodsAttribute> goodsAttributes) {


        int goodsTotal = 0;

        boolean isUpdate = goodsAttributes != null;

        List<GoodsAttribute> goodsAttributeListAdd = new ArrayList<>();
        for (String attributeValueCount :
                goodsDto.getAttributeValueCount()) {

            GoodsAttribute goodsAttribute = new GoodsAttribute();

            // 金额
            goodsAttribute.setGoodsAmount(new BigDecimal(attributeValueCount.split(",")[1].split("_")[0]));

            if (goodsAttribute.getGoodsAmount().compareTo(new BigDecimal(0)) == 0) {
                throw new CommonException(HttpStatus.BAD_NOT_PASS, "message.updateError-商品金额不能为0");
            }

            // 数量
            goodsAttribute.setGoodsCount(Integer.parseInt(attributeValueCount.split(",")[1].split("_")[1]));

            goodsTotal += Integer.parseInt(attributeValueCount.split(",")[1].split("_")[1]);

            // 商品Id
            goodsAttribute.setGoodsId(goods.getId());

            goodsAttribute.setAttributeName("");
            goodsAttribute.setAttributeValue("");
            String[] goodsAttributeList = attributeValueCount.split(",")[0].split("#");
            for (String attributeString :
                    goodsAttributeList) {
                // 属性
                goodsAttribute.setAttributeName(goodsAttribute.getAttributeName() + "_" + attributeString.split("_")[0]);
                // 属性值
                goodsAttribute.setAttributeValue(goodsAttribute.getAttributeValue() + "_" + attributeString.split("_")[1]);
            }
            goodsAttribute.setAttributeName(goodsAttribute.getAttributeName().substring(1, goodsAttribute.getAttributeName().length()));
            goodsAttribute.setAttributeValue(goodsAttribute.getAttributeValue().substring(1, goodsAttribute.getAttributeValue().length()));

            // 复用ID
            if (isUpdate) {
                for (GoodsAttribute goodsAttribute1 :
                        goodsAttributes) {
                    if (goodsAttribute1.getAttributeValue().equals(goodsAttribute.getAttributeValue())) {
                        goodsAttribute.setId(goodsAttribute1.getId());
                        break;
                    }
                }
            }
            goodsAttributeMapper.insert(goodsAttribute);
            goodsAttributeListAdd.add(goodsAttribute);
        }
        if (isUpdate) {
            LambdaQueryWrapper<BoxGroupGoods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(BoxGroupGoods::getGoodsId, goods.getId());
            List<BoxGroupGoods> boxGroupGoodsList = boxGroupGoodsMapper.selectList(lambdaQueryWrapper);

            // 判断boxGroupGoodsList中的每一个值是否存在于goodsAttributeListAdd中
            boolean isID = goodsAttributes.stream().allMatch(
                    boxGroupGoods -> goodsAttributeListAdd.stream().anyMatch(goodsAttribute -> goodsAttribute.getId().equals(boxGroupGoods.getId())));

            if (!isID) {
                throw new CommonException(HttpStatus.BAD_NOT_PASS, "message.updateError-该属性的商品在盲盒中，不允许删除");
            }
        }

        goods.setGoodsCount(goodsTotal);
        goodsMapper.updateById(goods);

    }

    /**
     * 商品 类别，图片  操作封装
     *
     * @param goodsDto 商品Dto
     * @param goods    商品
     * @return 商品
     */
    @Transactional
    public Goods goodsControls(GoodsDto goodsDto, Goods goods) {

        // 商品类别
        StringBuilder goodsTypeString = new StringBuilder();

        for (String goodsType :
                goodsDto.getGoodsType()) {
            goodsTypeString.append("_").append(goodsType);
        }
        goods.setGoodsType(goodsTypeString.substring(1, goodsTypeString.length()));


        // 币种
        goods.setMoneyTypeId(moneyTypeMapper.queryByCode("MYR").getId());

        // 主页图片
        if (goodsDto.getGoodsImages() != null && goodsDto.getGoodsImages().length > 0) {
            StringBuilder imagesString = new StringBuilder();
            for (String images :
                    goodsDto.getGoodsImages()) {
                imagesString.append("_").append(images);
            }
            goods.setGoodsImages(imagesString.substring(1, imagesString.length()));
        }
        // 中国描述图片
        if (goodsDto.getGoodsImageZh() != null && goodsDto.getGoodsImageZh().length > 0) {
            StringBuilder imagesString = new StringBuilder();
            for (String images :
                    goodsDto.getGoodsImageZh()) {
                imagesString.append("_").append(images);
            }
            goods.setGoodsImageZh(imagesString.substring(1, imagesString.length()));
        }

        // 马来西亚描述图片
        if (goodsDto.getGoodsImageMs() != null && goodsDto.getGoodsImageMs().length > 0) {
            StringBuilder imagesString = new StringBuilder();
            for (String images :
                    goodsDto.getGoodsImageMs()) {
                imagesString.append("_").append(images);
            }
            goods.setGoodsImageMs(imagesString.substring(1, imagesString.length()));
        }

        // 英文描述图片
        if (goodsDto.getGoodsImageEn() != null && goodsDto.getGoodsImageEn().length > 0) {
            StringBuilder imagesString = new StringBuilder();
            for (String images :
                    goodsDto.getGoodsImageEn()) {
                imagesString.append("_").append(images);
            }
            goods.setGoodsImageEn(imagesString.substring(1, imagesString.length()));
        }

        return goods;
    }

}
